
import { useEffect, useState } from 'react';
import { Button, Input, Tag,Radio,Space,message,Select  } from 'antd';

import { setData, getData } from '../methods';
import { USERList,USERAUTO } from '../const';
import { GlobalVal } from '../../global';
import { EnvComApi } from '../EnvList';
export const UserListApi = {}
window.UserListApi = UserListApi
const App = (props) => {
    const [tags, setTags] = useState([]);
    const [inputValue, setInputValue] = useState('');
    const [selected, selectedSet] = useState('');
    const [userSelected, userSelectedSet] = useState('');

    UserListApi.selected = selected
    UserListApi.userSelectedSet = userSelectedSet
    const selectData = tags.map(item => {
        return {
            label:item,
            value:item,
        }
    })
    const handleInputChange = (e) => {
        setInputValue(e.target.value);
    };

    const handleInputConfirm = () => {
        let userInfo = inputValue
        if (userInfo && !tags.includes(userInfo)) {
            if (!userInfo.includes('/')) {
                userInfo += '/123456a!'
            }
            setTags([...tags, userInfo]);                         
            setInputValue('');
        }
    };

    const handleTagClose = (tag) => {
        setTags(tags.filter((t) => t !== tag));
    };
    useEffect(() => {
        getData(USERList).then((userData) => {
            if (!userData || userData.length === 0) {
                userData = GlobalVal.userList
            }
            setTags(userData.map(item => {
                return `${item.name}/${item.pwd}`
            }))
        })            
        getData(USERAUTO).then((userAuto) => {
            console.warn('userAuto',userAuto)
            userSelectedSet(userAuto ? userAuto : undefined) // 设置undefined可以让select组件显示placeholder
        })            
    }, [])
    useEffect(() => {
        // 同步数据到chrome.storage.local
        let data = tags.map(item => {
            let info = item.split('/')
            return {
                name: info[0],
                pwd: info[1],
            }
        })
        setData(USERList, data)           
        // 同步消息到content中
        try {                
            chrome.tabs.query({
                active: true,
                currentWindow: true
            }, (tabs) => {
                chrome.tabs.sendMessage(tabs[0].id, data, res => {
                    console.log('popup=>content')
                })
            })                
        } catch (error) {
            
        }
        EnvComApi.optionsSet(selectData)
    }, [tags])    
    const onChange = (e) => {
        selectedSet(e.target.value)
    }    
    const handleChange = (value) => {
        userSelectedSet(value)
        setData(USERAUTO,value)
    }    
    // selectData.unshift({label:'无',value:''})
    return (
        <div style={{padding:'20px'}}>
            <Input
                type="text"
                size="small"
                value={inputValue}
                onChange={handleInputChange}
                onBlur={handleInputConfirm}
                onPressEnter={handleInputConfirm}
                style={{ width: '150px',marginRight:'10px' }}
                placeholder="kf1/123456a!"
            />
            <Button size="small" onClick={handleInputConfirm} title="在登录页面显示账号按钮，点击按钮可以进行登录">
                + 添加账号
            </Button>
            <Select
                defaultValue={''}
                size="small"
                style={{
                    width: 150,
                    marginLeft:20
                }}
                title={'自动登录账号，选中后，一打开环境登录页面就会自动登录此账号，清空则取消自动登录'}
                placeholder={'自动登录账号'}
                onChange={handleChange}
                onClear={()=>{handleChange('')}}
                options={selectData}
                value={userSelected}
                allowClear
                />             
            <div className='zhanghao-list'>
                {/* <Radio.Group onChange={onChange} value={selected}> */}
                        {tags.map((tag) => (
                            // <Radio key={tag} value={tag}>
                                <Tag color="orange" key={tag} closable onClose={() => handleTagClose(tag)} style={{marginBottom:10}}>
                                    {tag}
                                </Tag>
                            // </Radio>       
                        ))}
                {/* </Radio.Group>                 */}
            </div>
        </div>
    );
};

export default App;